<template>
    <div id="desDiv">
        <!-- 头部 -->
        <div id="headdiv">
            <span>库存预警</span>
        </div>
        <div id="sale">
            <el-button class="add-button" @click="showAddModal">新增库存设置</el-button>
        </div>
        <div id="customer-fenlei">
            <span> 超限库存分类： </span>
            <el-link  @click="handleClick('All')" class="link-font">全部&nbsp;</el-link>
            <el-link  @click="handleClick('Gao')" class="link-font">高库存&nbsp;</el-link>
            <el-link  @click="handleClick('Di')" class="link-font">低库存&nbsp;</el-link>
            <el-link  @click="handleClick('Ping')" class="link-font">平库存&nbsp;</el-link>
        </div>
        <div id="search-bar">
            <el-input placeholder="请输入仓库/物品/属性进行搜索" prefix-icon="el-icon-search" v-model="searchKeyword" @change="handleClick"></el-input>
        </div>
        <!-- 下划线分隔 -->
        <el-divider></el-divider>
        <!-- 躯干 -->
        <div>
            <el-table :data="customersData" border stripe class="centered-table"> 
                <el-table-column prop="ia_id" label="序号" ></el-table-column>
                <el-table-column prop="w_Name" label="库存名称"></el-table-column>
                <el-table-column prop="ia_goods_name" label="物品名称"></el-table-column>
                <el-table-column prop="ia_unit" label="单位"></el-table-column>
                <el-table-column prop="ia_goods_attribute" label="物品属性"></el-table-column>
                <el-table-column prop="ia_min_inventory" label="设置最低库存"></el-table-column>
                <el-table-column prop="ia_max_inventory" label="设置最高库存" ></el-table-column>
                <el-table-column prop="ia_system_inventory" label="系统库存" ></el-table-column>
                <el-table-column prop="ia_go_beyond" label="超限数量" ></el-table-column>
                <el-table-column label="操作" width="250">
                    <template slot-scope="scope">
                        <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">修改</el-button>
                        <el-button size="mini" type="danger" icon="el-icon-delete"  @click="handleDelete(scope.row.ia_id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 下划线分隔 -->
        <el-divider></el-divider>
        <!-- 尾部 -->
        <div id="taildiv">
           <!-- 分页 -->
        <el-pagination class="pagination"
            @size-change="change"
            @current-change="Ymchange"
            :current-page="currentPage"
            :page-sizes="[10, 20, 30, 40]" 
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper" 
            :total="rows">
        </el-pagination>
    <!-- 添加模态框 -->
    <el-dialog title="添加" :visible.sync="isAddModalVisible" width="400px" :close-on-click-modal="false">
      <el-form :model="form" label-width="100px">
        <el-form-item label="仓库名称*">
          <el-select v-model="form.w_Name" @change="handleSelectionChange('w_Name')"   autocomplete="off" placeholder="请选择仓库名称">
            <el-option 
              v-for="item in list"
              :key="item.w_Name"
              :label="item.w_Name"
              :value="item.w_Name">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="物品属性*">
          <el-select v-model="form.ia_goods_attribute" autocomplete="off" placeholder="请选择物品属性" @change="nation">
           <el-option 
              v-for="item in uniqueList"
              :key="item.di_type"
              :label="item.ia_goods_attribute"
              :value="item.di_type">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物品名称*">
          <el-select v-model="form.ia_goods_name"  @change="handleSelectionChange('ia_goods_name')" autocomplete="off" placeholder="请选择物品名称">
            <el-option 
              v-for="item in list3"
              :key="item.di_name"
              :label="item.ia_goods_name"
              :value="item.di_name">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="单位*">
          <el-select v-model="form.ia_unit" autocomplete="off" placeholder="请选择单位">
            <el-option 
              v-for="item in list4"
              :key="item.dd_label"
              :label="item.ia_unit"
              :value="item.dd_label">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="最低库存*">
          <el-input v-model="form.ia_min_inventory" autocomplete="off" placeholder="请输入设置最低库存"  class="input-text" maxlength="1000" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="最高库存*">
          <el-input v-model="form.ia_max_inventory" autocomplete="off" placeholder="请输入设置最高库存" class="input-text" maxlength="1000" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="超限数量*" v-if="islabel">
          <el-input v-model="overrun" auto-complete="off" placeholder="超限数量" class="input-text"></el-input>
        </el-form-item>
        <el-form-item label="系统库存*" v-if="islabel">
          <el-input v-model="form.ia_system_inventory" auto-complete="off" placeholder="系统库存"></el-input>
        </el-form-item>
        <el-form-item label="逻辑删除*" v-if="islabel">
          <el-input v-model="form.IsDeleted" auto-complete="off" placeholder="逻辑删除"></el-input>
        </el-form-item>
      </el-form>
      <div>
        <span slot="footer" style="display: flex; justify-content: center;">
          <el-button @click="isAddModalVisible = false"
            style="margin-right: 20px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">取消</el-button>
          <el-button type="primary" @click="submitForm"
            style="margin-left: 20px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">确定</el-button>
        </span>
      </div>
    </el-dialog>

     <!-- 修改模态框 -->
    <el-dialog title="修改" :visible.sync="isEditModalVisible" width="400px" :close-on-click-modal="false">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="库存预警ID" v-if="islabel">
          <el-input v-model="editForm.ia_id" autocomplete="off" placeholder="库存预警ID" ></el-input>
        </el-form-item>
        <el-form-item label="仓库名称">
          <el-select v-model="editForm.w_Name" autocomplete="off" placeholder="请选择仓库名称">
            <el-option 
              v-for="item in list"
              :key="item.w_Name"
              :label="item.w_Name"
              :value="item.w_Name">
              </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物品属性">
          <el-select v-model="editForm.ia_goods_attribute" autocomplete="off" placeholder="请选择物品属性">
            <el-option label="开始" value="开始"></el-option>
            <el-option label="结束" value="结束"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物品名称">
          <el-select v-model="editForm.ia_goods_name" autocomplete="off" placeholder="请选择物品名称">
            <el-option label="开始" value="开始"></el-option>
            <el-option label="结束" value="结束"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="单位">
          <el-select v-model="editForm.ia_unit" autocomplete="off" placeholder="请选择单位">
            <el-option label="开始" value="开始"></el-option>
            <el-option label="结束" value="结束"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="最低库存">
          <el-input v-model="editForm.ia_min_inventory" autocomplete="off" placeholder="请输入设置最低库存"  class="input-text"></el-input>
        </el-form-item>
        <el-form-item label="最高库存">
          <el-input v-model="editForm.ia_max_inventory" autocomplete="off" placeholder="请输入设置最高库存" class="input-text"></el-input>
        </el-form-item>


        <el-form-item label="超限数量" v-if="islabel">
          <el-input v-model="overrun" auto-complete="off" placeholder="超限数量" class="input-text"></el-input>
        </el-form-item>
        <el-form-item label="系统库存" v-if="islabel">
          <el-input v-model="editForm.ia_system_inventory" auto-complete="off" placeholder="系统库存"></el-input>
        </el-form-item>
        <el-form-item label="逻辑删除" v-if="islabel">
          <el-input v-model="editForm.IsDeleted" auto-complete="off" placeholder="逻辑删除"></el-input>
        </el-form-item>
      </el-form>
      <div>
        <span slot="footer" style="display: flex; justify-content: center;">
          <el-button @click="isEditModalVisible = false"
            style="margin-right: 20px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">取消</el-button>
          <el-button type="primary" @click="updateWaring"
            style="margin-left: 20px; background-color: #4FC1B0; border-color: #4FC1B0; color: #fff;">确定</el-button>
        </span>
      </div>
    </el-dialog>
    </div>
 </div>
</template>

<script>
import { MessageBox } from 'element-ui';
import $http from '@/routers/base';
export default {
  data() {
    return {
      list: [],
      list2: [],
      list3: [],
      list4: [],
      Invent:[],
      
      currentPage: 1, //当前页
      pageSize: 10, //每页显示数
      rows: 0, //总行数
      customersData:[],
      //超限库存分类
      All:"",   //全部
      Gao:"",   //高库存
      Di:"",    //低库存
      Ping:"",  //平库存
      searchKeyword:"",//搜索框
      isAddModalVisible: false,// 添加模态框
      form: {
        w_Name: '',
        ia_goods_name: '',
        ia_unit: '',
        ia_goods_attribute: '',
        ia_min_inventory: '',
        ia_max_inventory: '',
        ia_system_inventory: 0,
        ia_go_beyond: 0,  
        IsDeleted:false,
        systemInventoryValue:null,
      },
      islabel:false,

      isEditModalVisible: false,  //修改模态框
      editForm: {
        ia_id:'',
        w_Name: '',
        ia_goods_name: '',
        ia_unit: '',
        ia_goods_attribute: '',
        ia_min_inventory: 0,
        ia_max_inventory: 0,
        ia_system_inventory: 0,
        ia_go_beyond:0,  
        IsDeleted:false
      }
    };
  },
  computed: {
    // 计算属性，用于对从后端获取的物品属性列表进行去重
    uniqueList() {
      // 利用Set数据结构对数组进行去重
      const uniqueValues = [...new Set(this.list2.map(item => item.di_type))];
      // 根据去重后的值构造对象数组
      const uniqueList = uniqueValues.map(value => ({
        di_type: value,
      }));
      return uniqueList;
    },
  },

  methods: {
    //分页
    handleClick(category) {
    // 根据分类设置查询条件
    if (category === 'All') {
      this.Gao = false;
      this.Di = false;
      this.Ping = false;
    } else if (category === 'Gao') {
      this.Gao = true;
      this.Di = false;
      this.Ping = false;
    } else if (category === 'Di') {
      this.Gao = false;
      this.Di = true;
      this.Ping = false;
    } else if (category === 'Ping') {
      this.Gao = false;
      this.Di = false;
      this.Ping = true;
    }
    // 初始化查询条件
    this.where=`1=1`;
    if (this.Gao) {
      this.where += ' AND (ia_go_beyond > 0)';
    } else if (this.Di) {
      this.where += ' AND (ia_go_beyond < 0)';
    } else if (this.Ping) {
      this.where += ' AND (ia_go_beyond = 0)';
    }
    if(this.searchKeyword){
      this.where += `AND (w_Name LIKE '%${this.searchKeyword}%' OR ia_goods_name LIKE '%${this.searchKeyword}%' OR ia_goods_attribute LIKE '%${this.searchKeyword}%')`;
    }
    // 向后端请求数据，并更新客户数据和总条数
    $http.get('InventoryAlerts/GetFenYe', {
      params: {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        where:this.where,
      }
    }).then(res => {
        this.customersData =res.customersData;
        this.rows=res.rows;
    }).catch(error => {
      console.error('Error fetching client data: ', error);
    });
  },
    change: function(size) {
      this.pageSize = size;
      this.currentPage = 1;
      this.handleClick();
    },
    Ymchange: function(page) {
      this.currentPage = page;
      this.handleClick();
    },
    //查询仓库名称
    fetch(){
      $http
        .get("InventoryAlerts/IQuery")
          .then(res=>{
            this.list = res;
          })
          .catch(err => {
            alert(err);
          });
    },
    //查询物品属性
    property(){
      $http
        .get("InventoryAlerts/Query")
          .then(res=>{
            this.list2 = res;
          })
          .catch(err => {
            alert(err);
          });
    },
    //查询物品名称
    async nation(){
      this.form.ia_goods_name = "";
       if (this.form.ia_goods_attribute) {
         $http.get("InventoryAlerts/ResQuery?where=" + this.form.ia_goods_attribute)
          .then(res=>{
            this.list3 = res;
          })
          .catch(err => {
            alert(err);
          });
       }else {
        // 如果属性为空，清空物品名称列表
        this.list3 = [];
      }
    },
    //查询单位
    unit(){
      $http
        .get("InventoryAlerts/DictQuery")
          .then(res=>{
            this.list4 = res;
          })
          .catch(err => {
            alert(err);
          });
    },

    //添加按钮--打开添加页面
    showAddModal() {
      this.isAddModalVisible = true;
    },
    //添加非空判断
    validateForm(){
    if (this.form.w_Name.trim() === '') {
       this.$message.error('请选择仓库名称！');
        return false;
    }
    if (this.form.ia_goods_attribute.trim() === '') {
        this.$message.error('请选择商品属性');
        return false;
    }
    if (this.form.ia_goods_name.trim() === '') {
        this.$message.error('请选择物品名称');
        return false;
    }
    if (this.form.ia_unit.trim() === '') {
       this.$message.error('请选择单位');
        return false;
    }
    if (this.form.ia_min_inventory.trim() === '') {
        this.$message.error('请输入最低库存');
        return false;
    }
    if (this.form.ia_max_inventory.trim() === '') {
        this.$message.error('请输入最高库存');
        return false;
    }
    if(this.form.ia_min_inventory.trim() < this.form.ia_max_inventory.trim()){
        this.$message.error('最高库存必须大于最低库存');
        return false;
    }
    // 所有字段都不为空，表单验证通过
    return true;
  },
    //添加
    async submitForm(){
      if (this.validateForm()) {
       this.Inv={
          w_Name:this.form.w_Name,
          ia_goods_name:this.form.ia_goods_name,
          ia_unit:this.form.ia_unit,
          ia_goods_attribute:this.form.ia_goods_attribute,
          ia_min_inventory:this.form.ia_min_inventory,
          ia_max_inventory:this.form.ia_max_inventory,
          ia_system_inventory:this.systemInventoryValue,
          ia_go_beyond:this.form.ia_go_beyond,
          IsDeleted:false
       };
        $http.post('InventoryAlerts/Add',this.Inv)
          .then(response=>{
            if(response){
              this.form.w_Name='',
              this.form.ia_goods_name='',
              this.form.ia_unit='',
              this.form.ia_goods_attribute='',
              this.form.ia_min_inventory= '',
              this.form.ia_max_inventory= '',
              this.isAddModalVisible=false
              this.handleClick();
              this.$message.success('添加成功！');
            }else{
              this.$MessageBox.success('添加失败！请重新添加！');
            }
        }).catch(error=>{
          this.$message.error('添加失败:'+ error.$message);
        })
      }
    },
    //显示修改的值
    handleEdit(row){
      this.$set(this.editForm,'ia_id',row.ia_id);
      this.$set(this.editForm,'w_Name',row.w_Name);
      this.$set(this.editForm,'ia_goods_name',row.ia_goods_name);
      this.$set(this.editForm,'ia_unit',row.ia_unit);
      this.$set(this.editForm,'ia_goods_attribute',row.ia_goods_attribute);
      this.$set(this.editForm,'ia_min_inventory',row.ia_min_inventory);
      this.$set(this.editForm,'ia_max_inventory',row.ia_max_inventory);
      this.isEditModalVisible=true;
    },  
    //修改非空判断
    validateEditForm(){
        if (this.editForm.w_Name.trim() === '') {
        alert('请选择仓库名称！');
        return false;
    }
    if (this.editForm.ia_goods_attribute.trim() === '') {
        alert('请选择商品属性');
        return false;
    }
    if (this.editForm.ia_goods_name.trim() === '') {
        alert('请选择物品名称');
        return false;
    }
    if (this.editForm.ia_unit.trim() === '') {
        alert('请选择单位');
        return false;
    }
    if (this.editForm.ia_min_inventory.trim() === '') {
        alert('请输入最低库存');
        return false;
    }
    if (this.editForm.ia_max_inventory.trim() === '') {
        alert('请输入最高库存');
        return false;
    }
    // 所有字段都不为空，表单验证通过
    return true;
    },
    //修改
    async updateWaring(){
      console.log("修改的值：" + JSON.stringify(this.editForm));
      if(this.validateEditForm()){
        console.log("修改的值2：" +this.editForm);
        $http.put('InventoryAlerts/Update',this.editForm)
          .then(res=>{
            if(res){
              this.isEditModalVisible=false;
              this.handleClick();
              this.$message.success(' 修改成功！')
            }else{
              this.$message.error('修改失败！重试！')
            }
          }).catch(error=>{
            this.$message.error('修改失败：' + error.message);
          })
      }
    },
    //逻辑删除
    async handleDelete(ia_id) {
      MessageBox.confirm('确认删除删除该条记录吗？, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(()=>{
        $http.delete(`InventoryAlerts/Delete/${ia_id}`)
          .then(()=>{
            this.$message({
              type: 'success',
              message: '删除成功！'
            })
            this.handleClick();
          }).catch(error=>{
            this.$message.error('删除失败：'+error.message)
          })
      })
      .catch(() => {
          this.$message({
            type: 'info',
            message: '管理员取消了删除,删除无效哦！'
          })
        })
    },
    
    handleSelectionChange(field) {
      if (field == 'w_Name') {
        this.Inventory(this.form.w_Name, this.form.ia_goods_name);
      } else if (field == 'ia_goods_name') {
        this.Inventory(this.form.w_Name, this.form.ia_goods_name);
      }
    },
    Inventory(w_Name, ia_goods_name) {
      this.systemInventoryValue = null; 
      $http.get(`InventoryAlerts/InventoryQuery?w_Name=${w_Name}&ia_goods_name=${ia_goods_name}`)
        .then(res => {
          this.Invent = res;
          // 将Invent中获取到的igi_quantity值添加到customersData数组中
          this.customersData.forEach(item => {
          if (item.w_Name == w_Name && item.ia_goods_name == ia_goods_name) {
            this.$set(item, 'ia_system_inventory', this.Invent[0]); // 更新 customersData 中的值
            this.systemInventoryValue = this.Invent[0]; // 将获取到的值存储在组件变量中
            
            console.log(this.systemInventoryValue);
            console.log("数量值："+this.Invent[0]);
          }
        });
      })
      .catch(err => {
        alert(err);
      });
    }
  },
  mounted() {
    this.handleClick();
    this.fetch();
    this.property();
    this.unit();
   
  },
};
</script>

<style scoped src="../CSS/Warning.css"></style>
<style scoped>
#desDiv{
    width: 100%;
    height: 100%;
}
</style>